package com.aliyun.messagemgt.util;

import lombok.Getter;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.util.ObjectUtils;

/**
 * 容器工具类，提供获取bean实例方法
 *
 * @author : WangZhiPan
 * @date : 2021/9/23 14:50
 */

public class SpringUtils implements ApplicationContextAware {

    /**
     * -- GETTER --
     *  获取上下文
     *
     * @return
     */
    @Getter
    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (ObjectUtils.isEmpty(context)) {
            context = applicationContext;
        }
    }

    /**
     * 通过名称获取实例
     *
     * @param name
     * @return
     */
    public static Object getBean(String name) {
        return getContext().getBean(name);
    }

    /**
     * 通过class获取
     *
     * @param clazz
     * @return
     */
    public static <T> T getBean(Class<T> clazz) {
        return getContext().getBean(clazz);
    }


}
